package command

import (
	"github.com/pkg/errors"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"

	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils"
)

type Custom struct {
	BaseCommand
	Nodes        bkenode.Nodes
	CommandName  string
	CommandSpec  *agentv1beta1.CommandSpec
	CommandLabel string
}

func (c *Custom) Validate() error {
	if err := c.BaseCommand.validate(); err != nil {
		return err
	}
	if len(c.Nodes) == 0 {
		return errors.New("nodes is empty")
	}
	if c.CommandName == "" {
		return errors.New("commandName is empty")
	}
	if c.CommandSpec == nil {
		return errors.New("commandSpec is empty")
	}
	return nil
}

func (c *Custom) New() error {
	if err := c.Validate(); err != nil {
		return err
	}
	commandName := c.CommandName
	commandSpec := c.CommandSpec
	commandSpec.NodeSelector = getNodeSelector(c.Nodes)
	return c.newCommand(commandName, c.CommandLabel, commandSpec)

}

func (c *Custom) Wait() (error, []string, []string) {
	err, complete, successNodes, failedNodes := c.waitCommandComplete()
	// means all command not executed
	if !complete && len(failedNodes) == 0 {
		for _, node := range c.Nodes {
			if utils.ContainsString(successNodes, node.Hostname) {
				continue
			}
			failedNodes = append(failedNodes, node.Hostname)
		}
	}
	return err, successNodes, failedNodes
}
